layui.use(['table'], function() {
var table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    form = layui.form,
    laytpl = layui.laytpl,
    message = parent.message;
var tableIns = table.render({
    elem: '#demo',
    height: 'full-132', //容器高度
    url: '../sys/announcement/list?type=1&_'+$.now(),
    where: {sidx: '', order: 'desc'},
    page: true,
    id: 'demo',
    limit: 20,
    cols: [
        [{
            checkbox: true,
            fixed: true
        }, {
            field: 'annName',
            title: '公告名',
            width: 200,
            sort: true
        }, {
            field: 'annContent',
            title: '公告内容',
            width: 350
        }, {
            field: 'username',
            title: '发布人',
            width: 200
        },  {
            field: 'createTime',
            title: '创建时间',
            width: 200
        },{
            fixed: 'right',
            title: '操作',
            width: 200,
            align: 'center',
            toolbar: '#barDemo'
        }]
    ],
    done: function(res, curr, count) {
    	
    },
    loading: true,
});
form.render(null, 'kit-search-form');
$('#kit-search-more').on('click', function() {
    $('.kit-search-mored').toggle();
});
//监听工具条
table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'del') { //删除
        layer.confirm('确定删除该数据', function(index) {
            layer.close(index);
            //向服务端发送删除指令
            var userIds = Array();
            userIds.push(data.userId);
            $.ajax({
        		type: "POST",
        	    url: "../sys/user/delete",
        	    data: JSON.stringify(userIds),
        	    dataType: 'JSON',
        	    contentType: 'application/json',
        	    success: function(res){
        	    	if (res.code==0) {
        	        	message.show({
        	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
        	                msg:'操作成功'//提示信息
        	            });
        	        	obj.del(); //删除对应行（tr）的DOM结构
        	        	//tableIns.reload({where: {sidx: '', order: 'desc'}});
        	        } else {
        	        	layer.msg(res.msg, {icon: 2});
        	        }
        		}
        	});
        });
    } else if (layEvent === 'edit') { //编辑
    	$.get("../sys/announcement/info/"+data.id, function(res){
			if(res.code==0){
				$.get("../sys/user/select", function(r){
					if(r.code==0){
						var d = {
								announcement: {
									id:data.id,
									annName: data.annName,
									annContent:data.annContent
								},
								userList:r.list
				        };
				        laytpl($('#edit-tpl').html()).render(d, function(html) {
				            layer.open({
				                type: 1,
				                title: '修改用户信息',
				                content: html,
				                skin: 'layui-layer-rim', //加上边框
				                area: ['450px', '428px'],
				                btn: ['提交', '取消'],
				                yes: function(index, layero) {
				                    editIndex = index;
				                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
				                },
				                btn2: function(index, layero) {
				                	layer.close(index); //关闭弹出层
				                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
				                    return false;
				                },
				                success: function() {
				                    form.render(null, 'form-edit');
				                }
				            });
				        });
					}else {
			        	layer.msg(r.msg, {icon: 2});
			        }
				});
			}else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		});
    }
});

var roleList;
$(function(){
	$.get("../sys/role/select", function(r){
		roleList = r.list;
	});
});

$('.kit-search-btns').children('a').off('click').on('click', function() {
    var $that = $(this),
    action = $that.data('action');
    switch (action) {
        case 'add':
        	$.get("../sys/user/select", function(r){
        		if(r.code==0){
        			var d = {
        					announcement: {
								id:'',
								annName: '',
								annContent:''
							},
							userList:r.list
                    };
                    //渲染
                    laytpl($('#edit-tpl').html()).render(d,
                        function(html) {
                            layer.open({
                                type: 1,
                                title: '新增用户',
                                content: html,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['450px', '428px'],
                                btn: ['提交', '取消'],
                                yes: function(index, layero) {
                                    editIndex = index;
                                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                                },
                                btn2: function(index, layero) {
                                	layer.close(index); //关闭弹出层
                                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                                    return false;
                                },
                                success: function() {
                                    form.render(null, 'form-edit');
                                }
                            });
                        });
        		}else {
    	        	layer.msg(r.msg, {icon: 2});
    	        }
        	});
            break;
        case 'del-bulk':
            var d = table.checkStatus('demo');
            if (d.data.length === 0) {
                layer.msg('请选择要删除的数据');
                return;
            }
            var data = d.data,
                ids = [];
            layui.each(data, function(index, item) {
                ids.push(item.id);
            });
            layer.confirm('确定删除选中的数据', function(index) {
            	layer.close(index);
                //向服务端发送删除指令
                $.ajax({
            		type: "POST",
            	    url: "../sys/announcement/delete",
            	    data: JSON.stringify(ids),
            	    dataType: 'JSON',
            	    contentType: 'application/json',
            	    success: function(res){
            	    	if (res.code==0) {
            	        	message.show({
            	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
            	                msg:'操作成功'//提示信息
            	            });
            	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
            	        } else {
            	        	layer.msg(res.msg, {icon: 2});
            	        }
            		}
            	});
            });
            break;
        }
    });

var saveOrUpdate = function (datas) {
	var url = datas.id == null ? "../sys/announcement/save?type=1" : "../sys/announcement/update?type=1";
	console.log(JSON.stringify(datas));
	$.ajax({
		type: "POST",
	    url: url,
	    data: JSON.stringify(datas),
	    dataType: 'JSON',
	    contentType: 'application/json',
	    success: function(res){
	    	if (res.code==0) {
	        	message.show({
	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
	                msg:'操作成功'//提示信息
	            });
	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
	        } else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		}
	});
}

//监听搜索表单提交
form.on('submit(search)', function(data) {
	if(data.field.mobile!=""||data.field.status!=""||data.field.email!=""){
		$('.kit-search-mored').toggle();
	}
    if(data.field.status==""){
    	//带条件查询
        tableIns.reload({
        	where: {
        		sidx: '', order: 'desc',
        		annName: data.field.annName
        	}
        });
    }else{
    	//带条件查询
        tableIns.reload({
        	where: {
        		sidx: '', order: 'desc',
        		annName: data.field.annName
        	}
        });
    }
    return false;
});
var editIndex;
form.on('submit(formEdit)', function(data) {
	var roleIds = Array();
	$("input:checkbox[name='roleIdList']:checked").map(function (index, elem) {
		roleIds.push($(elem).val());
		});
	data.field.roleIdList = roleIds;
	saveOrUpdate(data.field);
	editIndex && layer.close(editIndex); //关闭弹出层
    return false;
});

});
